package com.example.smartcitydemo.ui.home.fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.example.smartcity_jscs.network.ResultStates.Resource.*
import com.example.smartcitydemo.NEWS_DETAIL
import com.example.smartcitydemo.R
import com.example.smartcitydemo.TYPE_ID
import com.example.smartcitydemo.base.BaseFragment
import com.example.smartcitydemo.bean.NewsInfo
import com.example.smartcitydemo.databinding.FragmentHomeNewsBinding
import com.example.smartcitydemo.ui.home.MyNewsAdapter
import com.example.smartcitydemo.ui.home.activity.NewsDetailActivity
import com.example.smartcitydemo.viewModel.home.HomeViewModel

/**
 * A simple [Fragment] subclass.
 * Use the [HomeNewsFragment.newInstance] factory method to
 * create an instance of this fragment.
 * 列表项包括图片、新闻标题、新闻内容缩	写（多出的字用省略号显示）、评论总数、发布时间等信息。
 */
class HomeNewsFragment : BaseFragment<FragmentHomeNewsBinding>(R.layout.fragment_home_news) {
    val homeViewModel: HomeViewModel by viewModels()

    val newsAdpter: MyNewsAdapter by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
        MyNewsAdapter()
    }

    companion object {
        @JvmStatic
        fun newInstance(typeId: Int) =
            HomeNewsFragment().apply {
                arguments = Bundle().apply {
                    putInt(TYPE_ID, typeId)
                }
            }
    }

    override fun initData() {
        arguments?.let {
            val int = it.getInt(TYPE_ID, 9)
            homeViewModel.getNewsInfo(int)

        }
    }

    override fun initView(bindView: FragmentHomeNewsBinding, savedInstanceState: Bundle?) {
        bindView.run {
            recyclerNews.adapter = newsAdpter.apply {
                setDiffCallback(NewsInfo.diffCallBack)
                setEmptyView(R.layout.loading_layout)
                setOnItemClickListener { adapter, view, pos ->
                    val newsDetailId = view.tag as Int
                    val intent = Intent(view.context, NewsDetailActivity::class.java)
                    intent.putExtra(NEWS_DETAIL,newsDetailId)
                    startActivity(intent)
                }
            }
        }

    }

    override fun addObservers(bindView: FragmentHomeNewsBinding) {
        homeViewModel.newsListData.observe(viewLifecycleOwner) {
            Log.d(TAG, "addObservers: $it")
            when (it) {
                is Success ->
                    newsAdpter.setDiffNewData(it.data!!.toMutableList())
                is Failure ->
                    newsAdpter.setEmptyView(R.layout.error_layout)
                is Loading ->
                    newsAdpter.setEmptyView(R.layout.loading_layout)
            }
        }
    }
}